package com.hs.srm.admin.modules.pricemanagement.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.common.util.ExcelUtil;
import com.hs.srm.admin.modules.pricemanagement.entity.*;
import com.hs.srm.admin.modules.pricemanagement.service.*;
import com.hs.srm.admin.modules.requisition.entity.*;
import com.hs.srm.admin.modules.requisition.service.*;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysRoleEntity;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysRoleService;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.common.validator.ValidatorUtils;
import com.hs.srm.common.validator.group.UpdateGroup;
import com.hs.srm.tools.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.mail.Account;
import sunnykid.mail.Mail;
import sunnykid.mail.Mail.MailAddress;
import sunnykid.mail.MailException;
import sunnykid.mail.SunnykidMail;
import sunnykid.text.SunnykidText;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 报价基本信息
 *
 * @author yanfei
 * @date 2019年3月11日
 */
@RestController
@RequestMapping("/inquiryQuotation")
public class InquiryQuotationController extends AbstractController {

    private static final long serialVersionUID = -4123823577744890422L;

    // 注入业务层
    @Autowired
    private InquiryQuotationService inquiryQuotationService;

    @Autowired
    private InquiryHeaderService inquiryHeaderService;

    @Autowired
    private InquiryItemService inquiryItemService;

    @Autowired
    private ParityEmailService parityEmailService;

    @Autowired
    private EssentialInformationService essentialInformationServiceImpl;

    @Autowired
    private NproPurchRequestHeaderService nproPurchRequestHeaderService;
    @Autowired
    private NproPurchRequestItemService nproPurchRequestItemService;
    @Autowired
    private ProPurchRequestHeaderService proPurchRequestHeaderService;
    @Autowired
    private ProPurchRequestItemService proPurchRequestItemService;
    @Autowired
    private SamplePurchRequestHeaderService samplePurchRequestHeaderService;
    @Autowired
    private SamplePurchRequestItemService samplePurchRequestItemService;
    @Autowired
    private VendorService vendorService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 保存报价的信息
     */
    @SysLog("保存报价的信息")
    @RequestMapping("/save")
    @RequiresPermissions("inquiry:save")
    public R save(InquiryQuotationEntity inquiryQuotationEntity) {
        return R.ok();
    }

    /**
     * 查询报价信息
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest resquest) {
        params.put("poFlag", resquest.getParameter("poFlag"));

        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        Long userId = username.getUserId();
        List<SysRoleEntity> sysRoleEntities = this.sysRoleService.findRoleName(userId);
        for (SysRoleEntity sysRoleEntity : sysRoleEntities) {
            String roleName = sysRoleEntity.getRoleName();
            if (roleName.equals("采购专员")) {
                String werks = username.getCompanyCode();
                params.put("werks", werks);
            }
        }
        // 查询用户列表
        PageUtils page = inquiryQuotationService.selectDetailPage(params);
        List<InquiryQuotationEntity> list = (List<InquiryQuotationEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }

    /**
     * 跳转至报价编辑页面
     *
     * @param
     * @return
     */
    @RequestMapping("/toEdit/{quotationId}")
    public ModelAndView toEdit(@PathVariable("quotationId") String quotationId) {
        InquiryQuotationEntity inquiryQuotationEntity = this.inquiryQuotationService.findbyId(quotationId);
        VendorInfoEntity vendorInfoEntity = this.vendorService.selectOne(new EntityWrapper<VendorInfoEntity>().eq("vendor_name", inquiryQuotationEntity.getVendorName()));
        if (vendorInfoEntity.getSrmCode() != null) {
            String taxCode = vendorInfoEntity.getTaxCode();
            inquiryQuotationEntity.setTaxCode(taxCode);
        } else {
            //查询税码
            String taxCode = inquiryQuotationService.getVendorTaxCode(inquiryQuotationEntity.getVendorCode());
            inquiryQuotationEntity.setTaxCode(taxCode);
        }
        // 把查询出来的对象赋值给供应商实体
        // ModelAndView modelAndView = new ModelAndView("modules/requisition/requisition_goodsdistribution_edit");
        ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/offer/offer_edit");
        modelAndView.addObject("inquiryQuotationEntity", inquiryQuotationEntity);
        return modelAndView;
    }

    /**
     * 更新报价单信息
     */
    @SysLog("更新报价单信息 ")
    @RequestMapping("/update")
    @RequiresPermissions("inquiry:update")
    public R update(InquiryQuotationEntity inquiryQuotationEntity) {
        ValidatorUtils.validateEntity(inquiryQuotationEntity, UpdateGroup.class);
        if (inquiryQuotationEntity != null) {
            inquiryQuotationEntity.setState(0);
            this.inquiryQuotationService.updateById(inquiryQuotationEntity);
            submit(inquiryQuotationEntity);
        }
        return R.ok();
    }

    /**
     * 报价单提交
     */
    @SysLog("报价单提交")
    public R submit(InquiryQuotationEntity inquiryQuotationEntity) {
        inquiryQuotationEntity = this.inquiryQuotationService.selectById(inquiryQuotationEntity.getQuotationId());
        //报价单已提交
        inquiryQuotationEntity.setState(1);
        //非生产性货源状态改变
        if (inquiryQuotationEntity.getRequestCode().contains("PR")) {
            nproPurchRequestHeaderService.changeGoodsStatus(NproPurchRequestHeaderEntity.YIBAOJIA, inquiryQuotationEntity.getRequestCode());
            nproPurchRequestItemService.changeGoodsStatus(NproPurchRequestItemEntity.YIBAOJIA, inquiryQuotationEntity.getNpkId());
        } else if (inquiryQuotationEntity.getRequestCode().contains("S")) {//样品申请单更改货源状态
            samplePurchRequestHeaderService.changeGoodsStatus(SamplePurchRequestHeaderEntity.YIBAOJIA, inquiryQuotationEntity.getRequestCode());
            samplePurchRequestItemService.changeGoodsStatus(SamplePurchRequestItemEntity.YIBAOJIA, inquiryQuotationEntity.getNpkId());
        } else {//生产性货源状态改变
            proPurchRequestHeaderService.changeGoodsStatus(ProPurchRequestHeaderEntity.YIBAOJIA, inquiryQuotationEntity.getRequestCode());
            proPurchRequestItemService.changeGoodsStatus(ProPurchRequestItemEntity.YIBAOJIA, inquiryQuotationEntity.getNpkId());
        }

        this.inquiryQuotationService.updateById(inquiryQuotationEntity);

        return R.ok();
    }

    // 发送报价提醒邮件
    @RequestMapping(value = "/sendMail", produces = "application/json; utf-8")
    @ResponseBody
    // 通过request获取到JSON请求参数
    public R SendMail(@RequestBody JSONObject obj) throws MailException {
        // 测试邮件发货功能
        Mail mail = new Mail("mail subject");
        String data = obj.toJSONString();
        JSONObject jsStr = JSONObject.parseObject(data);

        String[] str = ((String) jsStr.getJSONArray("arremail").get(0)).split(",");
        List<String> arremail = new ArrayList<String>(str.length);
        Collections.addAll(arremail, str);

        JSONArray arrinquiryCodelist = jsStr.getJSONArray("arrinquiryCodelist");
        JSONArray vendorNamelist = jsStr.getJSONArray("vendorNamelist");

        ParityEmail parityEmail = null;
        String strdate = DateUtils.getTime();
        List<ParityEmail> parityEmaillist = new ArrayList<ParityEmail>();
        List<MailAddress> receivers = new ArrayList<MailAddress>();
        String email = "";
        String strinquiryCode = "";
        for (int i = 0; i < arremail.size(); i++) {
            receivers.add(new MailAddress(arremail.get(i)));// 收件人
            email += arremail.get(i) + ",";
            // 这里可以添加多个收件人
        }
        email = email.substring(0, email.length() - 1);
        System.out.println("收件人的信息：" + email);

        for (int ii = 0; ii < arrinquiryCodelist.size(); ii++) {
            parityEmail = new ParityEmail();
            // 报价单
            parityEmail.setParityEmailInquiryCode(arrinquiryCodelist.get(ii).toString());
            // 邮件发送内容
            parityEmail.setData(DateUtils.stringToDate(strdate, DateUtils.DATE_TIME_PATTERN));
            // 主键id
            parityEmail.setParityEmailId(SunnykidText.getUUID());
            strinquiryCode += arrinquiryCodelist.get(ii).toString() + ",";
            parityEmaillist.add(parityEmail);
        }
        for (ParityEmail par : parityEmaillist) {
            par.setParityEmail(email);
        }
        // 对应供应商的名称
        for (int j = 0; j < vendorNamelist.size(); j++) {
            for (ParityEmail parity : parityEmaillist) {
                parity.setParityEmailVendorName(vendorNamelist.getString(j));
            }
        }
        // 发送的内容
        mail.setContent(strinquiryCode.substring(0, strinquiryCode.length() - 1));
        MailAddress sender = new MailAddress("yf761423958@163.com");// 发件人
        mail.setReceivers(receivers);
        mail.setSender(sender);
        Account account = new Account("smtp.163.com", "pop.163.com", "yf761423958", "yanfei521");
        SunnykidMail sMail = SunnykidMail.getInstance(account);
        try {
            sMail.sendMail(mail);
            // parityEmailService.insert(parityEmail);
            parityEmailService.insertBatch(parityEmaillist);
        } catch (MailException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }

        return R.ok("ok");
    }

    // 导出报价单
    @RequestMapping(value = "/Export")
    @ResponseBody
    public void Export(@Param(value = "quotationId []") String[] quotationId, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
        JSONArray studentArray = new JSONArray();
        for (String id : quotationId) {
            studentArray.add(inquiryQuotationService.findbyId(id));
        }
        /*
         * titleList存放了2个元素,分别为titleMap和headMap
         */
        ArrayList<LinkedHashMap> titleList = new ArrayList<LinkedHashMap>();
        // 1.titleMap存放了该excel的头信息
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>();
        titleMap.put("title1", "比价明细");
        titleMap.put("title2", "");
        // 2.headMap存放了该excel的列项
        LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("quotationId", "报价单ID");
        headMap.put("inquiryCode", "询价报价单号");
        headMap.put("inquiryId", "询价单ID");
        headMap.put("inquiryTotalCode", "汇总号");
        headMap.put("vendorCode", "供应商编码");
        headMap.put("vendorName", "供应商名称");
        headMap.put("price", "净价");
        headMap.put("totalPrice", "总价");
        headMap.put("priceUnit", "价格单位");
        headMap.put("poPriceUnit", "订单价格单位(采购)");
        headMap.put("taxCode", "销售/购买税代码");
        headMap.put("createdBy", "创建者");

        titleList.add(titleMap);
        titleList.add(headMap);

        String pathtem = SysConfig.getUploadPath() + File.separator;
        File file = new File(pathtem);
        if (!file.exists()) {
            file.mkdirs();// 创建该文件夹目录
        }
        OutputStream os = null;
        String Path = "";
        try {
            long start = System.currentTimeMillis();
            // .xlsx格式
            Path = file.getAbsolutePath() + File.separator + start + ".xlsx";
            os = new FileOutputStream(file.getAbsolutePath() + File.separator + start + ".xlsx");
            ExcelUtil.exportExcel(titleList, studentArray, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            os.close();
        }
        if (!"".equals(Path)) {
            boolean b = download(Path, response);
            if (b) {
                ExcelUtil.delete(file);
            }
        }
    }

    /**
     * 下载文件
     */
    public boolean download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            // response.setContentType("application/vnd.ms-excel;charset=gb2312");
            response.setHeader("content-type", "application/x-gzip");
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            // response.setHeader("Content-Disposition", headStr);

            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 更新信息记录
     *
     * @param pkId 报价单id
     * @param flag : false 非点价；true 点价，点价不同步SAP
     * @return
     */
    @SysLog("更新信息记录")
    @RequestMapping(value = "/updateSouce/{quotationId}")
    public R updateSouce(@PathVariable("quotationId") String pkId, boolean flag) {
        String[] result = pkId.split(",");
        for (int i = 0; i < result.length; i++) {
            //根据Id查询报价数据
            InquiryQuotationEntity inquiryQuotationEntity = this.inquiryQuotationService.findbyId(result[i]);
            if (inquiryQuotationEntity != null) {
                EssentialInformationEntity essentialInformation = this.essentialInformationServiceImpl.findByNo(inquiryQuotationEntity.getVendorCode(),
                        inquiryQuotationEntity.getWerks(), inquiryQuotationEntity.getMaterialCode(), "0");//classify:0信息记录默认标准类型
                if (essentialInformation != null) {
                    inquiryQuotationEntity.setState(InquiryQuotationEntity.STATE_XINXIJILUGENGXINGG);
                    inquiryQuotationEntity.setCreatedDate(new Date());
                    this.inquiryQuotationService.updateById(inquiryQuotationEntity);
                    this.essentialInformationServiceImpl.update(essentialInformation.getSrmCode(),
                            essentialInformation.getWerks(), essentialInformation.getMaterialCode(), result[i]);
                    //点价的，则设置不同步sap
                    if (flag) {
                        //获取更新后的数据
                        EssentialInformationEntity essential = essentialInformationServiceImpl.selectById(essentialInformation.getPkId());
                        essential.setInfoStatus(1);
                        essential.setWerks(null);
                        essentialInformationServiceImpl.updateById(essential);
                    }
                } else {
                    //新增
                    if (inquiryQuotationEntity != null) {
                        this.essentialInformationServiceImpl.insertInquiryQuoToEssntiaInfo(inquiryQuotationEntity);
                        //设置不同步，点价不同步sap
                        if (flag) {
                            //查出新增的信息记录
                            EssentialInformationEntity essential = essentialInformationServiceImpl.selectById(inquiryQuotationEntity.getQuotationId());
                            essential.setIsync(1);
                            essentialInformationServiceImpl.updateById(essential);
                        }

                        inquiryQuotationEntity.setState(InquiryQuotationEntity.STATE_XINXIJILUGENGXIN);
                        inquiryQuotationEntity.setCreatedDate(new Date());
                        this.inquiryQuotationService.updateById(inquiryQuotationEntity);

                    } else {
                        return R.error("没有此申请单号!");
                    }
                }
            } else {
                return R.ok("所选的报价单有错误!");
            }

        }
        return R.ok();
/*        //1.查询OA传递过来的报价信息
        List<InquiryQuotationEntity> inquiryQuotationList = this.inquiryQuotationService.findbyInquiryQuotation();
        //更新信息记录维护
        for (InquiryQuotationEntity inquiryQuotationEntity : inquiryQuotationList) {
            //根据条件查询出来
            EssentialInformationEntity essentialInformation = this.essentialInformationServiceImpl.findByNo(inquiryQuotationEntity.getVendorCode(),
                    inquiryQuotationEntity.getWerks(), inquiryQuotationEntity.getMaterialCode());


       }*/
    }


    /**
     * 下载附件
     */
    @RequestMapping("/downloadFile")
    public R downloadFile(@RequestParam(value = "inquiryItemId") String inquiryItemId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InquiryItemEntity itemEntity = inquiryItemService.selectById(inquiryItemId);
        if (itemEntity.getAttachment() == null || "".equals(itemEntity.getAttachment())) {
            return R.error("没有可下载的文件！");
        }
        String filePath = SysConfig.getUploadPath() + "/nproPurch_att/";
        String attachment = itemEntity.getAttachment();
        String[] fileNames = attachment.split(";");
        File[] files = new File[fileNames.length];
        for (int i = 0; i < fileNames.length; i++) {
            files[i] = new File(filePath + fileNames[i]);
        }
        //文件下载，多文件打包zip下载,单文件直接下载
        if (files.length > 1) {
            FileUtils.zipDownload(files, "附件下载", request, response);
        } else {
            FileUtils.fileDownload(files[0], request, response);
        }
        return R.ok();
    }


}
